package com.cabbagetofu.crowd.controller;


import com.atguigu.crowd.constant.CrowdConstant;
import com.atguigu.crowd.until.CrowdUtil;
import com.atguigu.crowd.until.ResultEntity;
import com.cabbagetofu.api.MySQLRemoteService;
import com.cabbagetofu.crowd.config.OSSProperties;
import com.cabbagetofu.crowd.entity.po.ProjectPO;
import com.cabbagetofu.crowd.entity.po.ReturnPO;
import com.cabbagetofu.crowd.entity.vo.*;
import com.netflix.ribbon.proxy.annotation.Http;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpSession;
import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;

@Controller
public class ProjectConsumerController {

    @Autowired
    private OSSProperties ossProperties;

    @Autowired
    private MySQLRemoteService mySQLRemoteService;

    /**
     * 访问详情更多
     */
    @RequestMapping("/more")
    public String showPortalMore(ModelMap modelMap){

        List<ProjectPO> allProjectRemote = mySQLRemoteService.getAllProjectRemote();
        modelMap.addAttribute("all_project", allProjectRemote);
        return "project-more";
    }

    @RequestMapping("/get/detail/project/{projectId}")
    public String getProjectDetail(@PathVariable("projectId") Integer projectId, ModelMap modelMap){

        // 根据id获取DetailProjectVO对象
        ResultEntity<DetailProjectVO> resultEntity = mySQLRemoteService.getDetailProjectVORemote(projectId);
        if (ResultEntity.SUCCESS.equals(resultEntity.getResult())){

            // 如果成功获取，则放入ModelMap中
            modelMap.addAttribute(CrowdConstant.ATTR_NAME_PROJECT_DETAIL, resultEntity.getData());
        }

        return "project-detail";
    }


    /**
     * 根据前端提交过来的“发起众筹项目”的表单数据，将这个数据全部都存入到对应的数据库表中
     * @param memberConfirmInfoVO
     * @param httpSession
     * @param modelMap
     * @return
     */
    @RequestMapping("/create/confirm")
    public String saveConfirmInfo(MemberConfirmInfoVO memberConfirmInfoVO, HttpSession httpSession, ModelMap modelMap){

        // 从session域中获取projectVO对象
        ProjectVO projectVO = (ProjectVO) httpSession.getAttribute(CrowdConstant.ATTR_NAME_TEMPLE_PROJECT);

        // 如果projectVO对象不存在，则抛出异常
        if (projectVO == null){

            throw new RuntimeException(CrowdConstant.MESSAGE_TEMPLE_PROJECT_MISSING);
        }
        // 如果正常则直接存放memberConfirmInfoVO对象
        projectVO.setMemberConfirmInfoVO(memberConfirmInfoVO);

        // 获取用户的登录信息
        MemberLoginVO memberLoginVO = (MemberLoginVO)httpSession.getAttribute(CrowdConstant.ATTR_NAME_LOGIN_MEMBER);
        // 获取用户的id
        Integer memberId = memberLoginVO.getId();

        // 根据用户id保存projectVO数据
        ResultEntity<String> saveProjectResult = mySQLRemoteService.saveProjectRemote(projectVO, memberId);

        // 如果保存失败，直接返回页面和错误信息
        if (saveProjectResult.getResult().equals(ResultEntity.FAILED)){

            modelMap.addAttribute(CrowdConstant.ATTR_NAME_MESSAGE, saveProjectResult.getMessage());
            return "project-confirm";
        }

        // 如果保存成功，将session域中的projectVO数据删除
        httpSession.removeAttribute(CrowdConstant.ATTR_NAME_TEMPLE_PROJECT);

        // 所有信息保存成功，即可去往“完成”页面
        return "redirect:http://localhost/project/create/success/page";

    }

    /**
     * 收集“回报设置”页面的表单数据，并放入session域中
     * @param returnVO
     * @param httpSession
     * @return
     */
    @ResponseBody
    @RequestMapping("/create/save/return.json")
    public ResultEntity<String> saveReturn(ReturnVO returnVO, HttpSession httpSession){

        try {
            // 从sessio域中拿到ProjectVO对象
            ProjectVO projectVO = (ProjectVO)httpSession.getAttribute(CrowdConstant.ATTR_NAME_TEMPLE_PROJECT);

            // 判断ProjectVO对象是否为空
            if (projectVO == null){

                // 为空则返回失败结果
                return ResultEntity.failed(CrowdConstant.MESSAGE_TEMPLE_PROJECT_MISSING);
            }

            List<ReturnVO> returnVOList = projectVO.getReturnVOList();

            // 如果ReturnVO为空，则new一个List空间
            if (returnVOList == null || returnVOList.size() == 0){

                returnVOList = new ArrayList<>();
                projectVO.setReturnVOList(returnVOList);
            }

            // 向returnVOList中存放当前接收的returnVO
            returnVOList.add(returnVO);

            // 更新session域中的ProjectVO对象
            httpSession.setAttribute(CrowdConstant.ATTR_NAME_TEMPLE_PROJECT, projectVO);

            // 全部操作正常，则返回成功结果
            return ResultEntity.successWithoutData();

        } catch (Exception e) {

            e.printStackTrace();
            return ResultEntity.failed(e.getMessage());
        }

    }


    /**
     * "回报设置"页面的上传图片需单独上传，即每点一次”上传图片“按钮，都是直接上传至服务器
     * @param returnPicture
     * @return
     * @throws IOException
     */
    @ResponseBody
    @RequestMapping("/create/upload/return/picture.json")
    public ResultEntity<String> uploadReturnPicture(MultipartFile returnPicture) throws IOException {

        // 判断上传的图片是否有效
        boolean returnPictureEmpty = returnPicture.isEmpty();
        if (returnPictureEmpty){

            return ResultEntity.failed(CrowdConstant.MESSAGE_RETURN_PIC_EMPTY);
        }

        // 将前端传过来的图片上传至OSS服务器
        ResultEntity<String> uploadReturnPictureResult = CrowdUtil.uploadFileToOss(ossProperties.getEndPoint(),
                ossProperties.getAccessKeyId(), ossProperties.getAccessKeySecret(),
                returnPicture.getInputStream(), ossProperties.getBucketName(),
                ossProperties.getBucketDomain(), returnPicture.getOriginalFilename());

        // 返回上传结果
        return uploadReturnPictureResult;

    }

    /**
     * @param projectVO             前端表单的数据自动装入ProjectVO对象
     * @param headerPicture         前端上传的头图
     * @param detailPictureList     前端上传的详情图片的list
     * @param httpSession           用于存放信息
     * @param modelMap              用于发生错误时传递信息
     * @return                      进入“回报设置”的页面
     * @throws IOException
     */
    @RequestMapping("/create/project/information")
    public String createProject(ProjectVO projectVO, MultipartFile headerPicture, List<MultipartFile> detailPictureList,
                                HttpSession httpSession, ModelMap modelMap) throws IOException {

        boolean headPictureEmpty = headerPicture.isEmpty();

        // --------上传头图----------
        // 判断用户是否上传了头图
        if (headPictureEmpty) {

            // 如果没有上传头图，则发送错误信息
            modelMap.addAttribute(CrowdConstant.ATTR_NAME_MESSAGE, CrowdConstant.MESSAGE_HEADER_PIC_EMPTY);
            // 返回至项目发起页面，重新填写表单
            return "project-launch";
        }

        // 如果上传了头图，就上传至OSS存储服务中
        ResultEntity<String> uploadHeadPictureResult = CrowdUtil.uploadFileToOss(ossProperties.getEndPoint(),
                ossProperties.getAccessKeyId(), ossProperties.getAccessKeySecret(),
                headerPicture.getInputStream(), ossProperties.getBucketName(),
                ossProperties.getBucketDomain(), headerPicture.getOriginalFilename());

        // 判断头图是否成功上传到了OSS中
        if (ResultEntity.SUCCESS.equals(uploadHeadPictureResult.getResult())) {

            // 获取图片访问路径
            String headPicturePath = uploadHeadPictureResult.getData();

            // 将头图的OSS存放路径存入至projectVO对象中
            projectVO.setHeaderPicturePath(headPicturePath);
        } else {

            // 发送错误信息
            modelMap.addAttribute(CrowdConstant.ATTR_NAME_MESSAGE, CrowdConstant.MESSAGE_HEADER_PIC_UPLOAD_FAILED);
            // 上传不成功则返回至项目发起页面，重新填写表单
            return "project-launch";
        }

        // --------上传详情图----------
        // 用来存放详情图OSS存放路径的集合
        List<String> detailPicturePathList = new ArrayList<>();

        // 如果整个详情图为空
        if (detailPictureList == null || detailPictureList.size() == 0){

            // 发送错误信息
            modelMap.addAttribute(CrowdConstant.ATTR_NAME_MESSAGE, CrowdConstant.MESSAGE_DETAIL_PIC_EMPTY);
            // 返回至项目发起页面，重新填写表单
            return "project-launch";
        }

        // 遍历detaillPictureList集合
        for (MultipartFile detailPicture : detailPictureList) {

            // 如果单个详情图为空
            if (detailPicture.isEmpty()){

                // 发送错误信息
                modelMap.addAttribute(CrowdConstant.ATTR_NAME_MESSAGE, CrowdConstant.MESSAGE_DETAIL_PIC_EMPTY);
                // 返回至项目发起页面，重新填写表单
                return "project-launch";
            }

            // 将详情图逐个上传至OSS服务器
            ResultEntity<String> uploadDetailPictureResult = CrowdUtil.uploadFileToOss(ossProperties.getEndPoint(),
                    ossProperties.getAccessKeyId(),
                    ossProperties.getAccessKeySecret(), detailPicture.getInputStream(), ossProperties.getBucketName(),
                    ossProperties.getBucketDomain(), detailPicture.getOriginalFilename());

            // 判断上传的结果
            String result = uploadDetailPictureResult.getResult();
            // 如果上传成功则获取其文件的路径
            if (ResultEntity.SUCCESS.equals(result)) {

                String detailPicturePath = uploadDetailPictureResult.getData();
                detailPicturePathList.add(detailPicturePath);
            }else {// 上传不成功

                // 发送错误信息
                modelMap.addAttribute(CrowdConstant.ATTR_NAME_MESSAGE, CrowdConstant.MESSAGE_DETAIL_PIC_UPLOAD_FAILED);
                // 上传不成功则返回至项目发起页面，重新填写表单
                return "project-launch";
            }

        }

        // 将存放了详情图片的访问路径放入projectVO中
        projectVO.setDetailPicturePathList(detailPicturePathList);

        // 将更新的projectVO存入Session域中
        httpSession.setAttribute(CrowdConstant.ATTR_NAME_TEMPLE_PROJECT, projectVO);

        // 前往下一个“回报设置”页面
        return "redirect:http://localhost/project/return/project/page";
    }

}
	